package xio.leetcode.java;

import xio.leetcode.java.base.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 94. Binary Tree Inorder Traversal (Medium)
 * 给定一个二叉树，返回它的中序 遍历。
 *
 * 示例:
 *
 * 输入: [1,null,2,3]
 *    1
 *     \
 *      2
 *     /
 *    3
 *
 * 输出: [1,3,2]
 */
public class LC94_InorderTraversal {

    List<Integer> result = new ArrayList<>();

    /**
     * 二叉树的中序遍历
     * 递归解法
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        dfs(root);
        return result;
    }

    private void dfs(TreeNode node){
        if (node == null){
            return;
        }
        dfs(node.left);
        result.add(node.val);
        dfs(node.right);
    }

    /**
     * 迭代解法
     */
    public List<Integer> inorderTraversal2(TreeNode root){
        TreeNode cur = root;
        Stack<TreeNode> stack = new Stack<>();
        while (cur != null || !stack.isEmpty()){
            while (cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode node = stack.pop();
            result.add(node.val);
            cur = node.right;
        }

        return result;
    }


}
